package com.duo.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.duo.constant.GlobalConstant;
import com.duo.constant.StatusConstant;
import com.duo.dto.EmployeeDTO;
import com.duo.dto.EmployeeLoginDTO;
import com.duo.dto.EmployeePageQueryDTO;
import com.duo.entity.Employee;
import com.duo.enums.errorcode.LoginCode;
import com.duo.exception.BaseException;
import com.duo.mapper.EmployeeMapper;
import com.duo.result.PageResult;
import com.duo.service.EmployeeService;
import com.duo.utils.JwtUtil;
import com.duo.utils.Md5Utils;
import com.duo.utils.RedisUtils;
import com.duo.vo.EmployeeQueryVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;


@Service
@Slf4j
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee>
        implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private RedisUtils redisUtils;


    /**
     * 员工登录
     * @param employeeLoginDTO
     * @return
     */
    public Object login(EmployeeLoginDTO employeeLoginDTO, String oldToken) {

        // 删除旧token
        if (StrUtil.isNotBlank(oldToken)) {
            redisUtils.deleteObject(GlobalConstant.ADMIN_TOKEN_PREFIX + JwtUtil.getToken(oldToken));
        }
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();
        //1、根据用户名查询数据库中的数据
        Employee employee = baseMapper.selectOne(new LambdaQueryWrapper<Employee>().eq(Employee::getUsername, username));
        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (ObjectUtil.isNull(employee)) {
            // 账号不存在
            log.error("账号不存在");
            throw new BaseException(LoginCode.PWD_ERROR);
        }
        // 密码比对
        if (!Md5Utils.getMd5(password).equals(employee.getPassword())) {
            // 密码错误
            throw new BaseException(LoginCode.PWD_ERROR);
        }
        if (employee.getStatus().equals(StatusConstant.DISABLE)) {
            // 账号被锁定
            throw new BaseException(LoginCode.BAN_ERROR);
        }
        String token = Md5Utils.getMd5(String.valueOf(System.currentTimeMillis()));
        redisUtils.setCacheObject(GlobalConstant.ADMIN_TOKEN_PREFIX + token, employee, GlobalConstant.TIME, TimeUnit.MINUTES);
        String jwt = JwtUtil.getJwt(token);
        HashMap<String, String> map = new HashMap<>();
        map.put("token", jwt);
        return map;
    }

    /**
     * 保存员工
     * @param employeeDTO
     */
    @Override
    public void save(EmployeeDTO employeeDTO) {
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO, employee);
        employee.setPassword(Md5Utils.getMd5(employee.getPassword()));
        employeeMapper.insert(employee);
        log.info("保存员工成功，员工信息：{}", employee);
    }

    /**
     * 分页查询员工
     * @param employeePageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery(EmployeePageQueryDTO employeePageQueryDTO) {
        Page<Employee> page = new Page<>(employeePageQueryDTO.getPage(), employeePageQueryDTO.getPageSize());
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(Employee::getName, employeePageQueryDTO.getName());
        queryWrapper.like(Employee::getUsername, employeePageQueryDTO.getName());
        queryWrapper.eq(Employee::getStatus, StatusConstant.ENABLE);
        Page<Employee> tmp = employeeMapper.selectPage(page, queryWrapper);
        PageResult pageResult = new PageResult();
        pageResult.setTotal(tmp.getTotal());
        pageResult.setRecords(tmp.getRecords().stream().map(employee -> {
            EmployeeQueryVO employeeQueryVO = new EmployeeQueryVO();
            BeanUtils.copyProperties(employee, employeeQueryVO);
            return employeeQueryVO;
        }).collect(java.util.stream.Collectors.toList()));
        return pageResult;
    }

    /**
     * 更新员工信息
     * @param employeeDTO
     */
    @Override
    public void update(EmployeeDTO employeeDTO) {
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO, employee);
        employeeMapper.updateById(employee);
        log.info("更新员工信息成功，员工信息：{}", employee);
    }

}
